/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SettleDlg.java
 *
 * Created on 2012-1-9, 15:12:15
 */
package billmanage;

import com.breeze.entity.Tbill;
import com.breeze.entity.Tcategory;
import com.breeze.entity.Tuser;
import com.breeze.entity.Tuserbill;
import com.breeze.service.ICoreService;
import com.breeze.util.Constants;
import com.breeze.util.SpringUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jdesktop.application.Action;

/**
 *
 * @author huateng
 */
public class SettleDlg extends javax.swing.JDialog {

    /** Creates new form SettleDlg */
    public SettleDlg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        coreService=(ICoreService)SpringUtil.getBean("coreService");
        initTable();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        settleTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        settleTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        settleTable.setName("settleTable"); // NOI18N
        jScrollPane1.setViewportView(settleTable);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(billmanage.BillManageApp.class).getContext().getActionMap(SettleDlg.class, this);
        jButton1.setAction(actionMap.get("settle")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(billmanage.BillManageApp.class).getContext().getResourceMap(SettleDlg.class);
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setAction(actionMap.get("preview")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(74, 74, 74)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(49, 49, 49)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(41, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SettleDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SettleDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SettleDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SettleDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                SettleDlg dialog = new SettleDlg(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable settleTable;
    // End of variables declaration//GEN-END:variables

    private String[] header=new String[]{"用户名","应付金额"};
    private ICoreService coreService;
    private List billList;
    private Map<Integer,BigDecimal> users=new HashMap<Integer,BigDecimal>();
    private Map<Integer,Tuser> userMap=new HashMap<Integer, Tuser>();
    private Map<Integer,Tcategory> cateMap=new HashMap<Integer, Tcategory>();

    private void initTable() {
        //初始化表
        
        //查出所以活跃账单
        Tbill example=new Tbill();
        example.setState(Constants.BILL_STATE_ACTIVE);
        billList=coreService.queryBillList(example);
        if(billList==null)
            billList=new ArrayList();
        
        
        for(Object o:billList){
            Tbill bill=(Tbill)o;
            BigDecimal fee=BigDecimal.valueOf(Double.parseDouble(bill.getFee()));
            //payman
            doMath(users, bill.getPaymanid(), null, fee);
            
            //responseMan
            Tuserbill userbill=new Tuserbill();
            userbill.setBillid(bill.getSeqid());
            List userbillList=coreService.queryUserbillList(userbill);
            BigDecimal eachFee=fee.divide(BigDecimal.valueOf((long)userbillList.size()),2,BigDecimal.ROUND_HALF_DOWN);
            for(Object obj:userbillList){
                Tuserbill ub=(Tuserbill)obj;
                doMath(users,ub.getUserid(),"-",eachFee);
            }
        }
        
        //显示
        Object[][] items=new Object[users.size()][2];
        int index=0;
        for(Integer id:users.keySet()){
            Tuser user=new Tuser();
            user.setSeqid(id);
            user=(Tuser)coreService.queryUserList(user).get(0);
            userMap.put(id, user);
            items[index][0]=user.getUsername();
            items[index][1]=users.get(id);
            ++index;
        }
        
        TableModel tm=new DefaultTableModel(items,header);
        settleTable.setModel(tm);
    }
    
    private void doMath(Map<Integer,BigDecimal> map,Integer id,String op,BigDecimal fee){
        if(map.get(id)==null){
            if("-".equals(op)){
                map.put(id, fee.multiply(BigDecimal.valueOf(-1L)));
            }else{
                map.put(id, fee);
            }
        }else{
            BigDecimal orignal=map.get(id);
            if("-".equals(op)){
                orignal=orignal.add(fee.multiply(BigDecimal.valueOf(-1L)));
                map.put(id, orignal);
            }else{
                orignal=orignal.add(fee);
                map.put(id, orignal);
            }
        }
    }

    @Action
    public void settle() {
        if(billList==null || billList.size()<=0)
            return;
        
        for(Object o:billList){
            Tbill bill=(Tbill)o;
            Tbill example=new Tbill();
            example.setSeqid(bill.getSeqid());
            example.setState(Constants.BILL_STATE_SETTLED);
            example.setSettleDt(Constants.DATE_FORMAT.format(new Date()));
            coreService.updateBill(example);
        }
        JOptionPane.showMessageDialog(this, "结算成功");
        initTable();
    }
    
    private String makeHtmlFile()
    {
        StringBuilder sb=new StringBuilder();
        BufferedReader br=null;
        try {
            InputStream is=getClass().getResourceAsStream("/com/breeze/util/htmlTemplate.tpl");
            br=new BufferedReader(new InputStreamReader(is,"utf-8"));
            while(br.ready()){
                String str=br.readLine();
                sb.append(str);
                System.out.println(str);
            }
        } catch (IOException ex) {
            Logger.getLogger(SettleDlg.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        sb.append("<tbody>");
        
        for(int i=0;i<billList.size();i++){//each tr
            Tbill bill=(Tbill)billList.get(i);
            
            if(i%2==1)
                sb.append("<tr class='odd'>");
            else
                sb.append("<tr>");
            
            sb.append("<td>"+bill.getBillno()+"</td>");
            sb.append("<td>"+bill.getRemark()+"</td>");
            sb.append("<td>"+bill.getFee()+"</td>");
            
            if(cateMap.get(bill.getCategoryid())==null){
                Tcategory cate=new Tcategory();
                cate.setSeqid(bill.getCategoryid());
                cate=(Tcategory)coreService.queryCategoryList(cate).get(0);
                cateMap.put(bill.getCategoryid(), cate);
            }
            
            sb.append("<td>"+cateMap.get(bill.getCategoryid()).getDisplay()+"</td>");
            sb.append("<td>"+userMap.get(bill.getPaymanid()).getUsername()+"</td>");
            
            sb.append("<td>");
            Tuserbill userbill=new Tuserbill();
            userbill.setBillid(bill.getSeqid());
            List l=coreService.queryUserbillList(userbill);
            for(Object o:l){
                userbill=(Tuserbill)o;
                sb.append(userMap.get(userbill.getUserid()).getUsername()+";");
            }
            sb.append("</td>");
            
            sb.append("<td>"+bill.getCreateDt()+"</td>");
            sb.append("</tr>");
        }//end of tr
        
        sb.append("</tbody></table>");
        
        //userbill table
        sb.append("<table><caption>应支付详细</caption><thead><tr class='odd'><th scope='col'>用户名</th><th scope='col'>应得金额</th></thead><tbody><tr>");
        int index=0;
        for(Integer id:users.keySet()){
            BigDecimal fee=users.get(id);
            Tuser u=userMap.get(id);
            
            if(index%2==1)
                sb.append("<tr class='odd'>");
            else
                sb.append("<tr>");
            
            sb.append("<td>"+u.getUsername()+"</td>");
            sb.append("<td>"+fee.toString()+"</td>");
            sb.append("</tr>");
            ++index;
        }
        sb.append("</tbody></table></body></html>");
        System.out.println(sb.toString());
        return sb.toString();
    }

    @Action
    public void preview() {
        //生成临时文件
        String path="D:\\temp\\"+Constants.DATE_FORMAT.format(new Date()) +".html";
        File file=new File(path);
        try {
            FileWriter fw=new FileWriter(file);
            fw.write(makeHtmlFile());
            fw.flush();
            fw.close();
        } catch (IOException ex) {
            Logger.getLogger(SettleDlg.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        JOptionPane.showMessageDialog(rootPane, "成功!");
    }
}
